package cn.tedu.straw.search.schedule;

import cn.tedu.straw.search.repository.QuestionRepository;
import cn.tedu.straw.search.service.IQuestionService;
import cn.tedu.straw.search.vo.QuestionSearchVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class LoadQuestionSchedule {
    @Autowired
    IQuestionService questionService;
    @Autowired
    QuestionRepository questionRepository;
    @Autowired
    ElasticsearchOperations elasticsearchOperations;
    @Scheduled(fixedRate = 1 * 60 * 1000)
  public void   writeQuestions2Elasticsearch(){
      // 先将ES服务器上对应的索引删除，以至于此前ES中存储的文档全部被删除
      IndexOperations indexOps = elasticsearchOperations.indexOps(QuestionSearchVO.class);
      indexOps.delete();
      // 循环读取MySQL中的数据，并写入到Elasticsearch中
      Integer pageNum = 1;
      PageInfo<QuestionSearchVO> pageInfo = null;
      do {
          pageInfo = questionService.getQuestionsFromDatabase(pageNum);
          pageNum++;
          questionRepository.saveAll(pageInfo.getList());
      } while (pageInfo.isHasNextPage());

  }
}
